<template>
  <div>
    <!-- 主要表格区 -->
    <div class="main_table_area">
      <!-- 按钮 -->
      <div class="op_btns">
        <!-- 上传视频 -->
        <div id="upload_container">
          <el-upload multiple :show-file-list="false" :action="mainTable.upload.action" :name="mainTable.upload.name"
            :headers="mainTable.upload.headers" :before-upload="beforeUploadHandle" :on-success="successHandle"
            :on-error="errorHandle">
            <el-button size="mini" type="success" :icon="videoAuths.uploadVideo.iconClass"
              v-show="uploadVideoStatus">上传视频</el-button>
          </el-upload>
        </div>
        <!-- 查看正在播放 -->
        <el-button plain size="mini" type="primary" icon="el-icon-video-pause" @click="showDrawer">查看正在播放</el-button>
        <!-- 批量删除 -->
        <el-button size="mini" type="danger" :icon="videoAuths.deleteVideos.iconClass" @click="toDeleteBatch"
          v-show="deleteVideosStatus">批量删除</el-button>
      </div>
      <!-- 主要表格 -->
      <div>
        <el-table border :data="mainTable.data" stripe size="mini" @selection-change="selectionChangeHandle">
          <template slot="empty">
            <el-empty description="什么视频都没有"></el-empty>
          </template>
          <!-- 操作列 -->
          <el-table-column width="100px" label="操作">
            <template slot-scope="{row}">
              <el-button plain size="mini" type="primary" icon="el-icon-video-play"
                @click="toPlaySelected(row)">播放</el-button>
            </template>
          </el-table-column>
          <!-- 复选列 -->
          <el-table-column type="selection"></el-table-column>
          <!-- 序号列 -->
          <el-table-column type="index" label="序号"></el-table-column>
          <!-- 展开列 -->
          <el-table-column type="expand" label="详情">
            <template slot-scope="{row}">
              <el-descriptions :title="row.originalFileName" :column="1" border size="small">
                <el-descriptions-item :label="col.label" v-for="col in mainTable.expandColumns" :key="col.id">
                  <span>{{ row[col.prop] }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </template>
          </el-table-column>
          <!-- 动态列 -->
          <el-table-column v-for="(col, index) in mainTable.columns" :key="index" :prop="col.prop" :label="col.label"
            :min-width="col.minWidth" show-overflow-tooltip>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="padding:10px; display: flex; justify-content:space-around; ">
          <el-pagination hide-on-single-page layout="total, sizes, prev, pager, next, jumper" next-text="下一页"
            prev-text="上一页" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="mainTable.page.currentPage" :page-size="mainTable.page.pageSize" :total="mainTable.page.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 视频播放抽屉 -->
    <div>
      <el-drawer show-close :title="videoDrawer.playing.originalFileName" direction="rtl"
        :before-close="beforeDisplayCloseHandle" :visible="videoDrawer.visible" size="70%">
        <video :src="videoDrawer.playing.visitUrl" controls :title="videoDrawer.playing.originalFileName"
          ref="videoRef"></video>
      </el-drawer>
    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      // 主表数据
      mainTable: {
        // 动态列
        columns: [
          {
            prop: 'originalFileName',
            label: '原名',
            sortable: true,
            minWidth: '80px',
          },
          {
            prop: 'size',
            label: '大小(Kb)',
            sortable: true,
            minWidth: '80px',
          },
          {
            prop: 'createAt',
            label: '上传时间',
            sortable: true,
            minWidth: '70px',
          },
        ],
        // 展开列
        expandColumns: [
          {
            prop: 'id',
            label: 'ID',
          },
          {
            prop: 'storeAbsolutePath',
            label: '存储位置',
          },
          {
            prop: 'visitUrl',
            label: '访问地址',
          },
          {
            prop: 'mimePrefix',
            label: '类型',
          },
          {
            prop: 'size',
            label: '大小(Kb)',
          },
          {
            prop: 'extend',
            label: '后缀',
          },
          {
            prop: 'originalFileName',
            label: '原名',
          },
          {
            prop: 'storeFileName',
            label: '存储名',
          },
          {
            prop: 'createAt',
            label: '上传时间',
          },
          {
            prop: 'creatorName',
            label: '上传者',
          },
          {
            prop: 'updateAt',
            label: '更新时间',
          },
          {
            prop: 'updaterName',
            label: '更新者',
          },
        ],
        // 表格数据
        data: [],
        // 表格选中数据
        selectedData: [],
        // 分页
        page: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 上传图片
        upload: {
          // 上传接口
          action: `${this.$axios.defaults.baseURL}admin/file/video`,
          // 参数名
          name: 'file',
          // 请求头
          headers: {
            token: sessionStorage.getItem('token'),
          },
        },
      },

      // 图片预览抽屉
      videoDrawer: {
        // 抽屉可见性
        visible: false,
        // 预览中视频
        playing: {
          visitUrl: '',
          originalFileName: '',
        },
      },
    }
  },

  computed: {
    // 借助mapGetters生成计算属性：videoAuths、uiAuthValidateIsNotNeeded
    ...mapGetters('uiAuthModule', ['uiAuthValidateIsNotNeeded', 'videoAuths']),
    // 各个操作可用状态计算属性
    uploadVideoStatus() {
      const { uploadVideo: { finalStatus } } = this.videoAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    deleteVideosStatus() {
      const { deleteVideos: { finalStatus } } = this.videoAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    getVideosStatus() {
      const { getVideos: { finalStatus } } = this.videoAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
  },

  methods: {
    //#region 主表方法开始
    // 分页查询
    async pagingGetVideos() {
      const { data: response } = await this.$axios.get(`/admin/file/video/${this.mainTable.page.currentPage}/${this.mainTable.page.pageSize}`)
      if (response.code === 0) {
        this.$message.error(response.msg)
        return
      }
      this.mainTable.data = response.data.data
      this.mainTable.page.total = response.data.total
    },
    // 分页组件参数变化处理
    handleSizeChange(pageSize) {
      this.mainTable.page.pageSize = pageSize
      this.pagingGetVideos()
    },
    handleCurrentChange(currentPage) {
      this.mainTable.page.currentPage = currentPage
      this.pagingGetVideos()
    },
    // 批量删除
    toDeleteBatch() {
      const fileDTOList = this.mainTable.selectedData.map(v => { return { "id": v.id, 'storeAbsolutePath': v.storeAbsolutePath } })
      if (fileDTOList != null && fileDTOList.length > 0) {
        this.$axios({
          method: 'delete',
          url: '/admin/file/video/batch',
          data: fileDTOList,
        })
          .then((response) => {
            this.$message.success(`${response.data.msg},已删除 ${response.data.data} 个视频`)
            this.mainTable.page.currentPage = 1
            this.pagingGetVideos()
          })
          .catch((err) => {
            this.$message.error(err.msg)
          })
      } else {
        this.$message.info('未选择要删除的视频')
      }
    },
    // 表格复选
    selectionChangeHandle(selection) {
      this.mainTable.selectedData = selection
    },
    // 播放选中视频
    toPlaySelected(video) {
      this.videoDrawer.playing = video
      this.showDrawer()
      this.$nextTick(() => {
        this.$refs.videoRef.play()
      })
    },
    //#endregion 主表方法结束

    //#region 视频播放方法开始
    // 展示抽屉
    showDrawer() {
      this.videoDrawer.visible = true
    },
    // 隐藏抽屉
    beforeDisplayCloseHandle(done) {
      const videoRef = this.$refs.videoRef
      if (!videoRef.paused) {
        this.$confirm("视频仍在播放中,确定退出并暂停播放吗?")
          .then(() => {
            this.videoDrawer.visible = false
            videoRef.pause()
            done()
          })
          .catch(() => { })
      } else {
        this.videoDrawer.visible = false
        done()
      }
    },
    //#endregion 视频播放方法结束

    //#region 视频上传方法开始
    // 成功回调
    successHandle(response, file) {
      if (response.code === 0) {
        this.$message.error(response.msg)
        return
      }
      this.$message.success(`${file.name}${response.msg}`)
      this.pagingGetVideos()
    },
    // 失败回调
    errorHandle(err, file) {
      this.$message.error(file.name + err.msg)
    },
    // 上传前检查，true指明能够上传
    beforeUploadHandle(file) {
      if (!/^video/i.test(file.type)) {
        this.$message.warning(`只能上传视频,文件类型为 ${file.name.substr(file.name.lastIndexOf('.') + 1)}`)
        return false
      }
      return true
    },
    //#endregion 视频上传方法结束
  },

  mounted() {
    // 若能够查询视频
    if (this.getVideosStatus) {
      this.pagingGetVideos()
    }
  }
}
</script>

<style lang="less" scoped>
.main_table_area {
  .op_btns {
    padding: 0 0 10px 0;

    #upload_container {
      display: inline-block;
      margin-right: 10px;

      .el-upload {
        display: inline-block;
      }
    }

  }
}

video {
  padding: 0px 10px 0px;
  width: 100%;
}
</style>